<?
 class Controller_Login extends Controller_Base {

 	function index($args) {
		
		$template = new Template('login.tmpl'); 		
		
		$user = new Model_User();
		
		if($user->is_logged()) 
			return array(
				status 		=> 302,
				location	=> '/'
			); 		
 		
 		$sigs = array(
 			'redirect'	=> array('type' => 'string','function'=>array('htmlspecialchars')),
		);			
		
		sanitize_vars($_REQUEST,$sigs,null); 
 	 		
	 		$redirect = $_REQUEST['redirect'] ? $_REQUEST['redirect'] : $_SERVER['HTTP_REFERER'];
	 		
			$template->setArg(redirect,$redirect);		
 		if($_POST['action'] === 'login') {

	 		$sigs = array(
	 			'user_name'	=> array('type' => 'string','function'=>array('htmlspecialchars'),'required' =>1),
	 			'password'	=> array('type' => 'string','function'=>array('htmlspecialchars'),'required' =>1),
			);			
			
			sanitize_vars($_POST,$sigs,null);

			
			// redirect back if form empty
			if(empty($_POST[user_name]) || empty($_POST[password])) 
				return array (
					status 		=> 302,	
					location	=> $_SERVER['HTTP_REFERER']
				);
			
			try{
				$SID = $user->login($_POST[user_name],$_POST[password]);
			} catch ( UserException $e ) {
//				error_log($e->getMessage());
			
				$template->setArgs(
					array(
						login_error				=> $e->getMessage(),
						do_not_show_login_form	=> 1,
					)
				);	
			}
			
			if($SID) {
				$cookie = array(
 					array( // session id
	 					name => 'SID',
	 					value => $SID,
	 					time  => time()+3600,
	 					path  =>  '/'
 					)
				);
			} else {
				// show login form if some error happen
	
		 		return array (
		 			status 		=> 0,
		 			template 	=> $template
		 		);				
			}

			return array (
				status 		=> 302,	
				location	=> $_REQUEST['redirect'] ? $_REQUEST['redirect'] : $_SERVER['HTTP_REFERER'], //'/' 
				cookies  	=> $cookie, 
			);
										
 		}		
		
		$template->setArg(do_not_show_login_form,1);
		$template->setArg(menu, $this->menu->getMenu(1));
 
 		return array (
 			status 		=> 0,
 			template 	=> $template
 		);
 		
 	}
 }
 
?>